package sfeir.ergosum.adapter;

import java.util.ArrayList;

import sfeir.ergosum.R;
import sfeir.ergosum.model.Person;
import sfeir.ergosum.model.Tel;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class PhoneAdapter extends BaseAdapter {

	private Context mContext;
	private LayoutInflater mInflater;
	private ArrayList<Tel> details;
	private Person p;
	private ViewHolder holder;

	public PhoneAdapter(Context c, Person p) {
		mContext = c;
		this.p = p;
		mInflater = LayoutInflater.from(mContext);
		details = new ArrayList<Tel>();
		populate();
	}

	public void update(Person newP) {
		p = newP;
		details.clear();
		populate();
		notifyDataSetChanged();
	}

	private void populate() {
		for (Tel t : p.getTels())
			details.add(t);
	}

	private static class ViewHolder {
		ImageView logo;
		TextView info;
	}

	@Override
	public int getCount() {
		return details.size();
	}

	@Override
	public Tel getItem(int position) {
		return details.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.list_item, null);

			holder = new ViewHolder();
			holder.logo = (ImageView) convertView.findViewById(R.id.list_item_image);
			holder.info = (TextView) convertView.findViewById(R.id.list_item_content);

			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		Tel t = getItem(position);
		

		final String tel = t.getPhoneNumber().replace(" ", "");

		OnClickListener telListener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel));
				mContext.startActivity(i);
			}
		};

		holder.info.setText(tel);
		convertView.setClickable(true);
		convertView.setOnClickListener(telListener);

		switch (t.getType()) {

		case Tel.MOBILE_LINE:
			holder.logo.setImageResource(R.drawable.phone_mobile);
			break;
		case Tel.HOME_LANDLINE:
			holder.logo.setImageResource(R.drawable.phone_perso);
			break;
		case Tel.PROFESSIONNAL_LINE:
			holder.logo.setImageResource(R.drawable.phone_pro);
			break;
		default:
			holder.logo.setImageResource(R.drawable.phone_perso);
			break;
		}
		
		return convertView;
	}

}
